import axios from 'axios';

const apiKey = 'e4068d1ed26205ef3d0bfac1d1e5cffd';

// 吉林省城市数据
export const jilinCities = [
  { name: '长春市', districts: ['南关区', '朝阳区', '宽城区', '二道区', '绿园区', '双阳区', '九台区'] },
  { name: '吉林市', districts: ['昌邑区', '龙潭区', '船营区', '丰满区'] },
  { name: '四平市', districts: ['铁西区', '铁东区'] },
  { name: '辽源市', districts: ['龙山区', '西安区'] },
  { name: '通化市', districts: ['东昌区', '二道江区'] },
  { name: '白山市', districts: ['浑江区', '江源区'] },
  { name: '松原市', districts: ['宁江区'] },
  { name: '白城市', districts: ['洮北区'] },
];

export interface WeatherData {
  city: string;
  district?: string;
  temperature: number;
  weather: string;
  humidity: number;
  windSpeed: number;
  icon: string;
}

export async function getWeatherByCity(city: string): Promise<WeatherData> {
  try {
    // 获取城市坐标
    const { data: locationData } = await axios.get(
      `https://api.openweathermap.org/geo/1.0/direct?q=${city},吉林省,CN&limit=1&appid=${apiKey}`
    );

    if (!locationData || locationData.length === 0) {
      throw new Error('城市未找到');
    }

    const { lat, lon } = locationData[0];

    // 获取天气数据
    const { data: weatherData } = await axios.get(
      `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${apiKey}&units=metric&lang=zh_cn`
    );

    return {
      city: city,
      temperature: Math.round(weatherData.main.temp),
      weather: weatherData.weather[0].description,
      humidity: weatherData.main.humidity,
      windSpeed: weatherData.wind.speed,
      icon: weatherData.weather[0].icon
    };
  } catch (error) {
    console.error('获取天气数据失败:', error);
    throw error;
  }
}

// 缓存天气数据
const weatherCache = new Map<string, { data: WeatherData; timestamp: number }>();
const CACHE_DURATION = 30 * 60 * 1000; // 30分钟缓存

export async function getCachedWeather(city: string): Promise<WeatherData> {
  const now = Date.now();
  const cached = weatherCache.get(city);

  if (cached && now - cached.timestamp < CACHE_DURATION) {
    return cached.data;
  }

  const weatherData = await getWeatherByCity(city);
  weatherCache.set(city, { data: weatherData, timestamp: now });
  return weatherData;
}
